package com.niiwoo.civet.trade.listener;

import com.alibaba.fastjson.JSON;
import com.niiwoo.civet.trade.constant.RabbitConstant;
import com.niiwoo.civet.trade.service.local.fund.FundRepaymentService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * 资金端 消息监听器
 *
 * @author lichuanzhi
 * @date 2018/01/26
 */
@Slf4j
@Component
public class FundListener{

    @Autowired
    private FundRepaymentService fundRepaymentService;

    /**
     * 自动更新标的状态和罚息
     * @param message 消息
     * @param channel 通道
     */
    @RabbitListener(queues = {RabbitConstant.Queue.FUND_REPAY_UPDATE_PENALTY})
    public void onMessage(Message message, Channel channel) {
        log.info("资金端 autoUpdatePenaltyAndProjectStatus 监听到消息:",JSON.toJSONString(message));
        try {
            String userId = JSON.parseObject(new String(message.getBody(), "UTF-8"), String.class);
            log.info("资金端 autoUpdatePenaltyAndProjectStatus listener--userId={}",userId);
            fundRepaymentService.autoUpdatePenaltyAndProjectStatus(userId);
        } catch (Exception e) {
            log.error("资金端 autoUpdatePenaltyAndProjectStatus 异常",e);
        }finally {
            doAckAnwser(message, channel);
        }
    }

    private void doAckAnwser(Message message, Channel channel) {
        try {
            //确认消息已经接收;
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (IOException ie) {
            log.error("basic ack occur exception, the reason is : {}", ie);
        }
    }
}
